package com.heima.user.controller.v1;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.excel.UserExcel;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.UserExcelService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.excel.EasyExcel;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;


//http://localhost:8080/service_6001/user/api/v1/apex/import
@Api(value = "app端用户批量导入",tags = "app端用户批量导入")
@RestController
@RequestMapping("/api/v1/apex")
public class UserExcelController {
    @Autowired
    private UserExcelService userExcelService;
    @PostMapping("/import")
    public ResponseResult imports( MultipartFile file){
        return userExcelService.simpleRead(file);
    }
    @GetMapping("/export")
    public ResponseResult export(HttpServletResponse response, @RequestParam("repetitionId") String name){
        return userExcelService.simpleWrite(response, name);
    }
//    @Autowired
//    private RedisTemplate<String,String> redisTemplate;
    /*@RequestMapping("/export")
    @RequestMapping("/export")
    //获取url链接上的参数
    public ResponseResult dowm(HttpServletResponse response, @RequestParam("repetitionId") String name){
        ApUser adminUser = AppThreadLocalUtils.getUser();
        response.setContentType("application/binary;charset=UTF-8");
        try{
            ServletOutputStream out=response.getOutputStream();
            try {
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name+".xls", "UTF-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }
            String range = String.valueOf(redisTemplate.opsForList().range(String.valueOf(adminUser.getId()), 0, -1));
            List<UserExcel> userExcels = JSON.parseArray(range, UserExcel.class);
            EasyExcel.write(out, UserExcel.class).sheet().doWrite(userExcels);
            return ResponseResult.okResult(userExcels);
        } catch(Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"导出失败");
        }
    }*/
}
